package net.jcip.examples.chapter6.thread.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletableFutureTest {

    public static void main(String[] args){

        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
                    return "hello from CF in " + Thread.currentThread().getName();
                })
                .thenApplyAsync(s -> s + " -> transformed")
                .whenComplete((r, ex) -> {
                    if (ex != null) System.out.println("err: " + ex);
                    else System.out.println("result: " + r);
                });
        String result = cf.join(); // 等待并得到结果（未包装异常或抛出 CompletionException）


        // 异步执行，无返回值
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " 执行任务");
        });


        // 异步执行，有返回值
        CompletableFuture<String> futureWithReturn = CompletableFuture.supplyAsync(() -> {
            return "任务结果：" + Thread.currentThread().getName();
        });


        //使用线程池执行
        ExecutorService executor = Executors.newFixedThreadPool(4);
        CompletableFuture<String> futureExecutor = CompletableFuture.supplyAsync(() -> {
            return "使用线程池执行";
        }, executor);



        //thenApply() —— 处理上一步结果并返回新结果
        CompletableFuture<String> applyResult = CompletableFuture
                .supplyAsync(() -> "Hello")
                .thenApply(s -> s + " World");
        System.out.println(applyResult.join()); // Hello World



        // thenAccept() —— 消费结果，无返回值
        CompletableFuture.supplyAsync(() -> "Hello")
                .thenAccept(s -> System.out.println("结果：" + s));


        //thenRun() —— 不依赖结果，只执行后续动作
        CompletableFuture.supplyAsync(() -> "Task Done")
                .thenRun(() -> System.out.println("后续任务执行"));




    }


}
